// node 39_手写深拷贝.js

let obj = {
    a:1,
    b:{
        b1:'b1',
        d:[1,2,3,4]
    },
}

let obj2 = obj

//浅拷贝
function copyObj(obj) {
    let res = {}
    for(let key in obj){
        if(obj.hasOwnProperty(key)) res[key] = obj[key]
    }
    return res
}

let obj3 = copyObj(obj)

obj2.a = 2
// obj3.b = 3
obj3.b.b1 = 'b3'

// console.log(obj)
// console.log(obj2)
// console.log(obj3)


//深拷贝-简易写法
function copyData(data) {

    //如果不是数组和方法则进行相应的返回
    if(data === null) return data
    if(data instanceof Date) return new Date(data)
    if(data instanceof RegExp) return new RegExp(data)
    if(typeof data !==  'object') return data

    let newDate = Array.isArray(data)?[]:{}//判断是数组还是方法

    Object.keys(data).forEach(key=>{//遍历内部属性
        newDate[key] = (typeof data[key] === 'object'  ) ? copyData(data[key]) : data[key]//如果内部还是引用类型则递归
    })
    return newDate
}

let obj4 = copyData(obj)
obj4.b.b1 = 'b4'
obj4.b.d[0] = 100

console.log(obj)
console.log(obj4)